﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcReservas.Models;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections;
using System.Text;

namespace MvcReservas.Controllers
{
    public class ReservaController : Controller
    {
        //
        // GET: /Reserva/

        private CanchitasWS.CanchitasClient proxy = new CanchitasWS.CanchitasClient();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Busqueda()
        {

            List<CanchitasWS.Canchita> canchitas = proxy.ListarCanchitas();
            var model = new Cliente
            {
                AvailableUsers = canchitas.Select(u => new SelectListItem
                {
                    Value = u.Codigo.ToString(),
                    Text = u.Nombre
                })
            };

            return View(model);
        }


        [HttpPost]
        public ActionResult Busqueda(FormCollection collection)
        {

            string dni = collection["dni"];
            string canchita = collection["SelectedUsers"];

            HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create("http://localhost:23374/Reservas.svc/Reservas/" + canchita + "/" + 0);
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string alumnoJson2 = reader2.ReadToEnd();
            JavaScriptSerializer js2 = new JavaScriptSerializer();

            List<Reserva> reservaObtenida = js2.Deserialize<List<Reserva>>(alumnoJson2);

            //Obtener el listado de reservas realizadas por el cliente
            req2 = (HttpWebRequest)WebRequest.Create("http://localhost:23374/Reservas.svc/Reservas/" + canchita + "/" + dni);
            req2.Method = "GET";
            res2 = (HttpWebResponse)req2.GetResponse();
            reader2 = new StreamReader(res2.GetResponseStream());
            alumnoJson2 = reader2.ReadToEnd();
            js2 = new JavaScriptSerializer();
            List<Reserva> reservasRealizadas = js2.Deserialize<List<Reserva>>(alumnoJson2);

            req2 = (HttpWebRequest)WebRequest.Create("http://localhost:26288/Clientes.svc/Clientes/" + dni);
            req2.Method = "GET";
            res2 = (HttpWebResponse)req2.GetResponse();
            reader2 = new StreamReader(res2.GetResponseStream());
            alumnoJson2 = reader2.ReadToEnd();
            js2 = new JavaScriptSerializer();
            Cliente clienteObtenido = js2.Deserialize<Cliente>(alumnoJson2);

           

            var model = new Reserva{
            listReserva = reservaObtenida,
            listReservaRealizada = reservasRealizadas,
            cliente = clienteObtenido.codigo,
            canchita = Int32.Parse(canchita)
            };

            return View("Reserva", model);
        }


        public List<Reserva> ObtenerListado(string canchita, string cliente)
        {
             HttpWebRequest req2;
            HttpWebResponse res2;
            StreamReader reader2;
            JavaScriptSerializer js2 = new JavaScriptSerializer();
            string alumnoJson2="";
            if(!cliente.Equals("0")){
                req2 = (HttpWebRequest)WebRequest.Create("http://localhost:26288/Clientes.svc/Customer/" + cliente);
                req2.Method = "GET";
                 res2 = (HttpWebResponse)req2.GetResponse();
                 reader2 = new StreamReader(res2.GetResponseStream());
                 alumnoJson2 = reader2.ReadToEnd();
                 js2 = new JavaScriptSerializer();
                Cliente clienteObtenido = js2.Deserialize<Cliente>(alumnoJson2);
                req2 = (HttpWebRequest)WebRequest.Create("http://localhost:23374/Reservas.svc/Reservas/" + canchita + "/" + clienteObtenido.dni);
                req2.Method = "GET";
                res2 = (HttpWebResponse)req2.GetResponse();
                reader2 = new StreamReader(res2.GetResponseStream());
                alumnoJson2 = reader2.ReadToEnd();
                js2 = new JavaScriptSerializer();
               
            }else{
                Cliente clienteObtenido = js2.Deserialize<Cliente>(alumnoJson2);
                req2 = (HttpWebRequest)WebRequest.Create("http://localhost:23374/Reservas.svc/Reservas/" + canchita + "/" + 0);
                req2.Method = "GET";
                res2 = (HttpWebResponse)req2.GetResponse();
                reader2 = new StreamReader(res2.GetResponseStream());
                alumnoJson2 = reader2.ReadToEnd();
                js2 = new JavaScriptSerializer();
            }
           
            List<Reserva> reservaObtenida = js2.Deserialize<List<Reserva>>(alumnoJson2);

            return reservaObtenida;
        }


        [HttpPost]
        public ActionResult Reserva(FormCollection collection)
        {
            string dia = collection["cboDia"];
            string hora = collection["cboHora"];
            string cantidad = collection["cantidad"];
            string cliente = collection["cliente"];
            string canchita = collection["cancha"];

            try
            {
                //Reservar
                Reserva res = new Reserva();
                res.canchita = Int32.Parse(canchita);
                res.cliente = Int32.Parse(cliente);
                res.cantidad = cantidad;
                res.diaHora = Int32.Parse(dia);
                res.dia = dia;
                res.hora = hora;
                res.estado = "0";
                res.fechaInicio = DateTime.Now;
                res.fechaFin = DateTime.Now;

                JavaScriptSerializer js = new JavaScriptSerializer();
                string json = js.Serialize(res);
                string postdata = json;
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23374/Reservas.svc/Reservas");
                req.Method = "POST";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var resp = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(resp.GetResponseStream());
                string alumnoJson = reader.ReadToEnd();
            } catch (WebException e) {
                HttpWebResponse resError = (HttpWebResponse)e.Response;//
                StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                string alumnoJson = reader2.ReadToEnd();
                JavaScriptSerializer js2 = new JavaScriptSerializer();
                Error error = js2.Deserialize<Error>(alumnoJson);
                ModelState.AddModelError(String.Empty, "Error: " + error.mensajeNegocio);
            }
           List<Reserva> reservaObtenida2= ObtenerListado(canchita, "0");
           List<Reserva> reservasRealizadas = ObtenerListado(canchita, cliente);


            var model2 = new Reserva
            {
                listReserva = reservaObtenida2,
                listReservaRealizada = reservasRealizadas,
                cliente = Int32.Parse(cliente),
                canchita = Int32.Parse(canchita)
            };

            return View("Reserva", model2);
        }


        public ActionResult Cancel(int id)
        {
            string idReserva = id.ToString();
            HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create("http://localhost:23374/Reservas.svc/Reservas/" + idReserva);
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string alumnoJson2 = reader2.ReadToEnd();
            JavaScriptSerializer js2 = new JavaScriptSerializer();
            Reserva reservaObtenida = js2.Deserialize<Reserva>(alumnoJson2);


            //Cancelar la reserva

            reservaObtenida.estado = "3";
            string json = js2.Serialize(reservaObtenida);
            string postdata = json; byte[] data = Encoding.UTF8.GetBytes(postdata);
            HttpWebRequest req = (HttpWebRequest)WebRequest.
                Create("http://localhost:23374/Reservas.svc/Reservas");
            req.Method = "PUT";
            req.ContentLength = data.Length;
            req.ContentType = "application/json";
            var reqStream = req.GetRequestStream();
            reqStream.Write(data, 0, data.Length);
            var res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());

            List<Reserva> reservaObtenida2 = ObtenerListado(reservaObtenida.canchita.ToString(), reservaObtenida.cliente.ToString());
            List<Reserva> reservasRealizadas = ObtenerListado(reservaObtenida.canchita.ToString(), "0");

            var model2 = new Reserva
            {
                listReserva = reservaObtenida2,
                listReservaRealizada = reservasRealizadas,
                cliente = reservaObtenida.cliente,
                canchita = reservaObtenida.canchita
            };

            return View("Reserva", model2);
        }

    }
}
